package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 上传文件接口
     * @param file 上传的文件
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件接口")
    public Result upload(@RequestParam MultipartFile file) {
        log.info("上传文件:{}",file);
        String filename = file.getOriginalFilename();//获取文件名
        String extendedName = filename.substring(filename.lastIndexOf('.'));//获取文件扩展名
        String uuid = UUID.randomUUID().toString();
        String objectName = uuid + extendedName;
        log.info("objectName:{}",objectName);
        String url = null;
        try {
            url = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(url);
        } catch (IOException e) {
            log.info("文件上传失败");
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
